/**
 * 
 */
package com.maywide.jdp.system.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.system.bean.OperatorBean;
import com.maywide.jdp.system.bean.OrganizationBean;
import com.maywide.jdp.system.entities.Operator;
import com.maywide.jdp.system.entities.Organization;
import com.maywide.jdp.system.entities.Role;

/**
 * <b>登录Service</b><br>
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Controller
public class IndexController {
	/**
	 * 单点登录会话ID
	 */
	public static final String SESSION_ID = "edu.yale.its.tp.cas.client.filter.operator";

	/**
	 * 用户Bean接口
	 */
	private OperatorBean bean = null;

	/**
	 * 机构Bean接口
	 */
	private OrganizationBean organizationBean = null;

	/**
	 * @param bean
	 *            the bean to set
	 */
	@Autowired
	@Qualifier("operatorBean")
	public void setBean(OperatorBean operatorBean) {
		this.bean = operatorBean;
	}

	/**
	 * @param organizationBean
	 *            the organizationBean to set
	 */
	@Autowired
	@Qualifier("organizationBean")
	public void setOrganizationBean(OrganizationBean organizationBean) {
		this.organizationBean = organizationBean;
	}

	@RequestMapping(value = "/entry.json")
	public void entry(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String operatorID = request.getRemoteUser();
		Operator operator = (Operator) bean.findByOperatorID(operatorID);
		Context context = setContext(operator);
		session.setAttribute("context", context);
		if(context.getOrganizations() != null && context.getCurrentOrganization() == null)
			response.sendRedirect("/desktop/selectEntity.html");
		else
			response.sendRedirect("/desktop/desktop.html");
	}

	/**
	 * @param operator
	 * @return
	 * @throws Exception
	 * @throws SysException
	 */
	private Context setContext(Operator operator) throws Exception {
		Context context = fillBaseContext(operator);
		String[] activeOrganizations = context.getOrganizations();
		if (activeOrganizations == null) {
			List<Role> activeRoles = getActiveRoles(operator);
			context = fillRoleContext(context, activeRoles);
		} else {
			int num = activeOrganizations.length;
			if (num == 1) {
				List<Role> activeRoles = getActiveRoles(operator);
				context = fillRoleContext(context, activeRoles);
				String currentOrganizationStr = activeOrganizations[0];
				context.setCurrentOrganization(currentOrganizationStr);
				String currentOrganizationID = currentOrganizationStr
						.split(",")[0];
				Organization currentOrganization = (Organization) organizationBean
						.load(currentOrganizationID);
				StringBuffer buf = new StringBuffer(currentOrganizationID);
				Organization parent = currentOrganization.getParent();
				while (parent != null) {
					buf.append("/").append(parent.getId());
					parent = parent.getParent();
				}
				context.setOrgPath(buf.toString());
			}
		}
		return context;
	}

	/**
	 * @param operator
	 * @return
	 */
	private Context fillBaseContext(Operator operator) {
		Context context = new Context();
		context.setId(String.valueOf(operator.getId()));
		context.setOperatorID(operator.getOperatorID());
		context.setOperatorname(operator.getOperatorname());
		context.setMobile(operator.getMobile());
		context.setEmail(operator.getEmail());

		List<Organization> organizations = operator.getOrganizations();
		List<Organization> activeOrganizations = null;
		if (organizations != null && !organizations.isEmpty()) {
			for (Organization organization : organizations) {
				if (!organization.isActive())
					continue;
				if (activeOrganizations == null)
					activeOrganizations = new ArrayList<Organization>();
				activeOrganizations.add(organization);
			}
		}
		if (activeOrganizations != null && !activeOrganizations.isEmpty()) {
			String[] orgArray = new String[activeOrganizations.size()];
			int i = 0;
			for (Organization org : activeOrganizations) {
				StringBuffer buf = new StringBuffer();
				buf.append(org.getId());
				buf.append(",");
				buf.append(org.getCode());
				buf.append(",");
				buf.append(org.getName());
				buf.append(",");
				buf.append(org.getType());
				orgArray[i] = buf.toString();
				i++;
			}
			context.setOrganizations(orgArray);
		}
		String[] orgArray = context.getOrganizations();
		if (orgArray == null || orgArray.length == 0) {
			List<Role> roles = operator.getRoles();
			fillRoleContext(context, roles);
		}
		return context;
	}

	private Context fillRoleContext(Context context, List<Role> roles) {
		if (roles != null && !roles.isEmpty()) {
			String[] roleArray = new String[roles.size()];
			int i = 0;
			for (Role role : roles) {
				if (!role.isActive())
					continue;
				StringBuffer buf = new StringBuffer();
				buf.append(role.getId());
				buf.append(",");
				buf.append(role.getCode());
				buf.append(",");
				buf.append(role.getName());
				buf.append(",");
				buf.append(role.getEntity());
				roleArray[i] = buf.toString();
				i++;
			}
			context.setRoles(roleArray);
		}

		return context;
	}

	/**
	 * @param operator
	 * @return
	 */
	private List<Role> getActiveRoles(Operator operator) {
		List<Role> roles = operator.getRoles();
		List<Role> activeRoles = null;
		if (roles != null && !roles.isEmpty()) {
			for (Role role : roles) {
				if (!role.isActive())
					continue;
				if (activeRoles == null)
					activeRoles = new ArrayList<Role>();
				activeRoles.add(role);
			}
		}
		return activeRoles;
	}

}
